package com.example.crm.controller;

import com.example.crm.entity.Users;
import com.example.crm.service.UsersService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;


@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    // 注册
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody Users user) {
        try {
            Users registeredUser = usersService.register(user);
            registeredUser.setPassword(null);
            return ResponseEntity.ok(registeredUser);
        } catch (IllegalStateException e) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
        }
    }

    // 登录
    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody LoginRequest loginRequest) {
        Optional<Users> userOptional = usersService.login(loginRequest.getUsername(), loginRequest.getPassword());
        if (userOptional.isPresent()) {
            Users user = userOptional.get();
            user.setPassword(null);
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }

    // 查询所有用户
    @GetMapping
    public ResponseEntity<?> getAllUsers() {
        return ResponseEntity.ok(usersService.findAll());
    }

    // 新增用户（人员管理用，非注册）
    @PostMapping
    public ResponseEntity<?> createUser(@RequestBody Users user) {
        try {
            Users createdUser = usersService.save(user);
            createdUser.setPassword(null);
            return ResponseEntity.ok(createdUser);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    // 根据ID更新用户
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Integer id, @RequestBody Users user) {
        try {
            user.setId(id);
            Users updatedUser = usersService.save(user);
            updatedUser.setPassword(null);
            return ResponseEntity.ok(updatedUser);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    // 根据ID删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Integer id) {
        usersService.deleteById(id);
        return ResponseEntity.ok().build();
    }

    @Data
    static class LoginRequest {
        private String username;
        private String password;
    }

    // 修改密码
    @PostMapping("/change-password")
    public ResponseEntity<?> changePassword(@RequestBody ChangePwdRequest req) {
        boolean success = usersService.changePassword(req.getUsername(), req.getOldPwd(), req.getNewPwd());
        if (success) {
            return ResponseEntity.ok("密码修改成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("原密码错误或用户不存在");
        }
    }

    @Data
    static class ChangePwdRequest {
        private String username;
        private String oldPwd;
        private String newPwd;
    }
}